package xdu.lz.stage2_design_pattern.chapter3_observer_pattern.observerApp3;

import java.util.List;

public class ThreadLifeCycleObserver implements ThreadLifeCycleListener {

    //不止监视一个线程，准备锁
    private static final Object LOCK = new Object();


    /**
     * 每个id开启了一个ObserverRunnable的run来监视
     * ObserverRunnable是一个抽象类实现了Runnable接口
     * @param ids
     */
    public void concurrentQuery(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        ids.forEach(id -> new Thread(
                //这里维护者主题，用主题来监视观察者内部线程的生命周期
                //一旦生命周期发生变化 ，则通知观察者notifyChange(内部调用观察者的onEvent方法)
                new ObserverRunnable(this) {
            @Override
            public void run() {
                try {
                    notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                    System.out.println("query for the id " + id);
                    Thread.sleep(1000L);
                    //int x = 1 / 0;
                    notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
                } catch (Exception e) {
                    notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));

                }
            }
        }, id).start());
    }


    /**
     * 当主题发生变化时，对应的操作
     * @param event
     */
    @Override
    public void onEvent(ObserverRunnable.RunnableEvent event) {
        synchronized (LOCK) {
            System.out.println("the runnable [" + event.getThread().getName() + "] data changed and " +
                    "state is [" + event.getState() + "]");
            if (event.getCause() != null) {
                System.out.println("the runnable [" + event.getThread().getName() + "] process failed");
                event.getCause().printStackTrace();
            }
        }
    }
}
